#!/usr/bin/perl
#Programmer: Rory
#Get Reciprocal Best Hits from the extracted hits of a blast file
#Modified to get one for each organism, this may be tricky

my %forward = ();
my %fmax = ();
my %backward = ();
my %bmax = ();
while ( my $line = <>) {
	chomp $line;
	my @splitline = split(/\t/, $line);
	my $q = [split(/\s+/,$splitline[0])]->[1];
	my $r = [split(/\s+/,$splitline[1])]->[0];
	my $score = $splitline[-2];
#	print "examining $q $r $score\n";
	if (!defined($fmax{$q}) || $score > $fmax{$q}) {
		$fmax{$q} = $score;
		$forward{$q} = $r;
	}
	if (!defined($bmax{$r}) || $score > $bmax{$r}) {
		$bmax{$r} = $score;
		$backward{$r} = $q;
	}
}
while (my ($key, $val) = each(%forward)) {
	if ($key eq $backward{$val}) {
		print "$key\t$val\t$fmax{$key}\n";
	}
}
